import * as vscode from 'vscode';

import * as Path from 'path';

import * as Fs from 'fs';
import { log } from 'console';

const pluginName = 'hello-plugin';

export default function (context: vscode.ExtensionContext){
  return [
    // hello world
    vscode.commands.registerCommand('hello.helloWorld', () => {
      vscode.window.showInformationMessage(`Hello World from ${pluginName}!`);
    }),
    // 菜单指令
    vscode.commands.registerCommand('hello.getCurrentFilePath', (uri) => {
      vscode.window.showInformationMessage(`当前文件(夹)路径是：${uri ? uri.path : '空'}`);
    }),
    // 打开webview
    vscode.commands.registerCommand('hello.openWebview', function (uri) {
      // 创建webview
      const panel = vscode.window.createWebviewPanel(
        'testWebview', // viewType
        "WebView演示", // 视图标题
        vscode.ViewColumn.One, // 显示在编辑器的哪个部位
        {
          enableScripts: true, // 启用JS，默认禁用
          // retainContextWhenHidden: true, // webview被隐藏时保持状态，避免被重置
        }
      );
      /***  读取图片得到相对路径到html模板 start ***/
      const onDiskPath = vscode.Uri.file(
        // Path.join(context.extensionPath, 'src/assets/images', 'chrome.png')
        Path.join(context.extensionPath, '/images', 'chrome.png')
      );
      // 得到路径 
      const catGifSrc = panel.webview.asWebviewUri(onDiskPath);
      
      // 页面输出的内容
      panel.webview.html = genWebview(catGifSrc);
      /***  读取图片得到相对路径到html模板 end ***/
      
      // 读取html 
      // const pathToHtml = vscode.Uri.file(
      //   Path.join(context.extensionPath, 'src', 'views/index.html')
      // );

      /******** 资源路径 start ******/
      // const srcPathUri = vscode.Uri.file(Path.join(context.extensionPath, 'src', 'views'));
      // const baseUri = panel.webview.asWebviewUri(srcPathUri);

      // const pathUri = pathToHtml.with({ scheme: 'vscode-resource' });
      // var indexHtml = Fs.readFileSync(pathUri.fsPath, 'utf8');
      // indexHtml = indexHtml.replace('<base href=/>', `<base href="${String(baseUri)}/">`);

      // panel.webview.html = indexHtml;
      /******** 资源路径 end ******/



      // 接收消息
      panel.webview.onDidReceiveMessage(message => {
        console.log('插件收到的消息：', message);
        // vscode.window.showErrorMessage(message.text);

        if (message.cmd) {
          // cmd表示要执行的方法名称
          messageHandler.command(message.cmd, message);
        } else {
          messageHandler.log(`未找到名为 ${message.cmd} 的方法!`);
        }

      }, undefined, context.subscriptions);
    }),
    vscode.commands.registerCommand('hello.webFormGen', function (uri) {
      // 创建webview
      const panel = vscode.window.createWebviewPanel(
        'form', // viewType
        "表单页2222", // 视图标题
        vscode.ViewColumn.One, // 显示在编辑器的哪个部位
        {
          enableScripts: true, // 启用JS，默认禁用
          retainContextWhenHidden: true, // webview被隐藏时保持状态，避免被重置
        }
      );

      // 读取html 
      const pathToHtml = vscode.Uri.file(
        Path.join(context.extensionPath, 'views', 'formGen/index.html')
      );

      /******** 资源路径 start ******/
      const srcPathUri = vscode.Uri.file(Path.join(context.extensionPath, 'views', 'formGen'));
      const baseUri = panel.webview.asWebviewUri(srcPathUri);

      const pathUri = pathToHtml.with({ scheme: 'vscode-resource' });
      var indexHtml = Fs.readFileSync(pathUri.fsPath, 'utf8');
      indexHtml = indexHtml.replace('<base href="/">', `<base href="${String(baseUri)}/">`);
      panel.webview.html = indexHtml;
      /******** 资源路径 end ******/
      


      // 接收消息
      panel.webview.onDidReceiveMessage(message => {
        console.log('插件收到的消息：', message);
        if (message.cmd) {
          // cmd表示要执行的方法名称
          messageHandler.command(message.cmd, message);
        } else {
          messageHandler.log(`未找到名为 ${message.cmd} 的方法!`);
        }

      }, undefined, context.subscriptions);

    }),
    // 生成文件
    vscode.commands.registerCommand('hello.genFile', (params) => {
      console.log(params);
      const { dir, fileName, content } = params;

      try {
        const rootPath = vscode.workspace.rootPath || '';
        const path = Path.join(rootPath, dir, fileName);
        Fs.writeFileSync(path, `${content}`);
        vscode.window.showInformationMessage(`生成成功 ${path}`);
      } catch (e) {
        console.log(e);
        vscode.window.showInformationMessage(`生成失败 ${e}`);
      }
    }),
    

    vscode.commands.registerCommand("helloPlugin-tools.openChild", args => {
      vscode.window.showInformationMessage(args);
    })
  ];
}

const messageHandler = {
  command(commandName: string, message: any){
    vscode.commands.executeCommand(`hello.${commandName}`, message.params);
    // 'hello.helloWorld';
  },
  log(msg: string){
    vscode.window.showInformationMessage(`${msg} !`);
  }
};


function genWebview(catGifSrc: vscode.Uri){
  
  return `<!DOCTYPE html>
    <html>
      <body>
        你好，我是Webview
        <img src="${catGifSrc}" />
      </body>
    </html>`;
}